package org.liang.exception;

import org.liang.util.AjaxResult;
import org.liang.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice //拦截产生异常
public class GlobalExceptionHandler {
    //对异常进行处理
    @ExceptionHandler(Exception.class)
    public AjaxResult systemException(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_500.getCode())
                .setMessage(ResponseCode.RESPONSE_CODE_500.getMessage());
    }

    //业务异常
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessException(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setCode(e.getCode()).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult jsr303Exception(MethodArgumentNotValidException e){
        e.printStackTrace();
        Map map = new HashMap<>();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_400.getCode())
                .setMessage(e.getMessage())
                .setResultObj(map);
    }
}
